package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author atguigu-mqx
 */
@Component
public class OrderReceiver {


    @Autowired
    private OrderService orderService;

    //  必须要制作一个配置类！
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId, Message message, Channel channel){
        /*
        1.  先判断当前的订单Id 是否为空！
            true:
                不为空，根据这个orderId,将订单取消！
                本质：更改状态！
            false:
        2.  手动确认消息！
         */
        //  判断
        try {
            if(orderId!=null){
                //  根据这个订单id来获取订单信息！
                //  select * from order_info where id = orderId;
                OrderInfo orderInfo = orderService.getById(orderId);
                //  判断是否支付了
                if ("UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())){
                    //  取消订单！
                    orderService.execExpiredOrder(orderId);
                }
            }
        } catch (Exception e) {
            //  如果消费未成功，，则记录日志，数据！
            e.printStackTrace();
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听支付模块发送的支付成功消息，队形但状态进行更新
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY, durable = "true",
            autoDelete = "false"), exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY), key =
            {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void updateOrderStatus(Long orderId, Message message, Channel channel) {
        try {
            //  判断
            if (orderId != null) {
                OrderInfo orderInfo = orderService.getById(orderId);
                //  订单处于未支付的时候，更新未支付
                if ("UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())){
                    //  执行更新状态
                    orderService.updateOrderStatus(orderId, ProcessStatus.PAID);
                    //  发送消息给库存。需要orderInfo中的数据，同时还需要orderDetail中的数据
                    orderService.sendOrderStatus(orderId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  手动确认消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听库存消息，并更新订单状态！
    //  {"orderId":"230","status":"DEDUCTED"}
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void updateOrder(String strJson, Message message, Channel channel) {
        try {
            //  判断
            if (!StringUtils.isEmpty(strJson)) {
                //  将字符串转换为Map
                Map map = JSON.parseObject(strJson, Map.class);
                String orderId = (String) map.get("orderId");
                String status = (String) map.get("status");
                //  急需判断
                if ("DEDUCTED".equals(status)) {
                    //  更新订单状态
                    this.orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.WAITING_DELEVER);
                } else {
                    this.orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.STOCK_EXCEPTION);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //  手动确认消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
